package com.bsoft.wx.config.shiro;

import com.bsoft.wx.pojo.TbUser;
import com.bsoft.wx.service.TbUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * @author hdh
 * @ Data   :Created in 22:01 2023/1/31
 * @ Description 自定义Realm
 * @ Modified By: hdh
 * @ Version : 1.0
 */
@Slf4j
@Component
public class OAuth2Realm extends AuthorizingRealm {
    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private TbUserService tbUserService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof OAuth2Token;
    }

    //认证（登录调用）
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //TODO 从令牌中获取userId，然后检测该账户是否被冻结。34.
        String accessToken = (String) authenticationToken.getPrincipal();
        int userId = jwtUtil.getUserId(accessToken);

        TbUser tbUser = tbUserService.searchById(userId);
        if (tbUser == null) {
            throw new LockedAccountException("账户已被锁定,请联系管理员");
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(tbUser, accessToken, getName());
        //TODO 往info对象中添加用户信息、Token字符串36.
        return info;
    }

    //授权(验证权限时调用)
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        TbUser tbUse = (TbUser) principals.getPrimaryPrincipal();
        int userId = tbUse.getId();
        //用户权限列表
        Set<String> permissions = tbUserService.searchUserPermissions(userId);
        log.info("权限" + permissions);

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(permissions);
        //TODO 查询用户的权限列表25.
        // TODO 把权限列表添加到info对象中26.
        return info;
    }

}
